<template>
  <PageWrapper title="前后端通信">
    <div class="mt-2">
      <a-card title="后端返还信息 Viewer">
        <BasicForm
          :labelWidth="100"
          :schemas="schemas"
          :actionColOptions="{ span: 24 }"
          @submit="handleSubmit"
        />

        <MarkdownViewer :value="value" />
      </a-card>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
import { defineComponent, ref, unref, h, toRaw } from 'vue';
import { BasicForm, FormSchema } from '/@/components/Form/index';
import { MarkDown, MarkDownActionType, MarkdownViewer } from '/@/components/Markdown';
import { PageWrapper } from '/@/components/Page';
import { Card } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { connTestAction } from '/@/api/sys/form_action';

const valueRef = ref(`
# title

# content
`);

const schemas: FormSchema[] = [
  {
    field: 'markdown',
    component: 'Input',
    label: 'markdown',
    defaultValue: valueRef,
    rules: [{ required: true, trigger: 'blur' }],
    render: ({ model, field }) => {
      return h(MarkDown, {
        value: model[field],
        onChange: (value: string) => {
          model[field] = value;
        },
      });
    },
  },
];

async function handleSubmit(values: any) {
  const { createMessage } = useMessage();
  try {
    createMessage.success('click search,values:' + JSON.stringify(values));
    console.log(values.markdown);
    // window.open(`mailto:meetings@openharmony.io?subject=[SIG申请]&body=${values.markdown}`)
    const actionStatus = await connTestAction(toRaw(values));
    if (actionStatus) {
      console.log('actionStatus: ', actionStatus);
      if (actionStatus.result) {
        createMessage.success(JSON.stringify(actionStatus));
      } else {
        createMessage.error(JSON.stringify(actionStatus));
      }
    } else {
      createMessage.error('No return value.');
      console.log('No return value.');
    }
  } catch (error) {
    console.error(error);
  }
};

export default defineComponent({
  components: { BasicForm, MarkDown, PageWrapper, MarkdownViewer, ACard: Card, valueRef },
  setup() {
    const markDownRef = ref<Nullable<MarkDownActionType>>(null);

    function toggleTheme() {
      const markDown = unref(markDownRef);
      if (!markDown) return;
      const vditor = markDown.getVditor();
      vditor.setTheme('dark');
    }

    function handleChange(v: string) {
      valueRef.value = v;
    }

    function clearValue() {
      valueRef.value = '';
    }

    return {
      value: valueRef,
      toggleTheme,
      markDownRef,
      handleChange,
      clearValue,
      schemas,
      handleSubmit,
    };
  },
});
</script>
